package com.song.secure.service;

import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;

import com.song.secure.bean.User;

public class RoleServiceImpl implements RoleService{
	
	private JdbcTemplate jdbcTemplate;
	
	
	@Override
	public Map<String, Collection<ConfigAttribute>> getAllConfigAttribute() {
		String sql ="select  *  from sys_role srl , sys_role_right srr , sys_right  srt "
				      + " where srl.id = srr.role_id and  srr.right_id = srt.id";
		
		Map<String, Collection<ConfigAttribute>> attibs = new  HashMap<String, Collection<ConfigAttribute>>(); 
		List<Map<String,Object>> mapps =   jdbcTemplate.queryForList(sql);
		
		for(Map<String,Object>  map :mapps)
		{
			String url = map.get("right_url").toString();
			String role = map.get("right_security").toString();
			if(attibs.containsKey(url))
			{
				Collection<ConfigAttribute> data =  attibs.get(url);
				data.add(new SecurityConfig(role));
				attibs.put(url,data);
			}
		}
		
		
		return attibs;
	}


	public JdbcTemplate getJdbcTemplate() {
		return jdbcTemplate;
	}


	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}


	@Override
	public User getUserByName(String name) {
		
		String sql ="select * from sys_user where usr_name =? ";
		
		Map<String,Object> map  = this.jdbcTemplate.queryForMap(sql, name);
		
		User usr = new User(map.get("usr_name").toString(), map.get("usr_password").toString() );
		
		int role_id = Integer.parseInt( map.get("usr_role_id").toString());
		
		
		String rsql ="select role_security from sys_role where id =?";
		
		String role  =	this.jdbcTemplate.queryForList(rsql, role_id, String.class).get(0).toString();
		GrantedAuthority authority = new GrantedAuthorityImpl(role);
		Set<GrantedAuthority> authSet = new HashSet<GrantedAuthority>();
		authSet.add(authority);
		usr.setAuthorities(authSet);
		return usr;
	}

	
	
	
}
